package com.zhsecurity.service.impl;

import com.zhsecurity.exception.VerificationCodeException;
import com.zhsecurity.service.VerificationCodeService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Random;

public class VerificationCodeServiceImpl implements VerificationCodeService {
    private static final int DEFAULT_WIDTH = 80;
    private static final int DEFAULT_HEIGHT = 40;
    private static final int DEFAULT_LINES = 10;
    private static final String SESSION_KEY = "security_verification_code";

    private int width = DEFAULT_WIDTH;
    private int height = DEFAULT_HEIGHT;

    public VerificationCodeServiceImpl() {
    }

    public VerificationCodeServiceImpl(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public BufferedImage createVerificationCode(HttpServletRequest request) {
        String code = "";

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        //设置背景色
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);//画背景
        //填充指定的矩形。使用图形上下文的当前颜色填充该矩形
        //设置字体
        g.setFont(new Font("宋体", Font.BOLD, 18));
        //随机数字
        Date d = new Date();
        Random r = new Random(d.getTime());
        for (int i = 0; i < 4; i++) {
            int a = r.nextInt(10);//取10以内的整数[0，9]
            int y = 10 + r.nextInt(20); //10~30范围内的一个整数，作为y坐标
            Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
            g.setColor(c);
            g.drawString("" + a, 5 + i * width / 4, y);
            code += a;
        }
        //干扰线
        for (int i = 0; i < DEFAULT_LINES; i++) {
            Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
            g.setColor(c);
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
        g.dispose();

        HttpSession session = request.getSession();
        session.setAttribute(SESSION_KEY, code);
        return img;
    }

    public Boolean checkVerificationCode(HttpServletRequest request, String inputCode) {
        HttpSession session = request.getSession();
        if (session == null) {
            throw new VerificationCodeException("验证码错误!");
        }
        Object object = session.getAttribute(SESSION_KEY);
        if (object == null) {
            throw new VerificationCodeException("验证码失效!");
        }
        String code = (String) object;
        if (!code.equals(inputCode)) {
            throw new VerificationCodeException("验证码错误!");
        }
        return true;
    }
}
